<script setup>
import { ref, defineProps, reactive, computed, onMounted, watch, onUpdated } from 'vue'
const lineText = ref(null)
const mockLyric = ref(`
[00:00:00]我爱歌词网www.5ilrc.com\n
[00:03:12]没有你的夜\n
[00:05:37]演唱/和声：夏婉安＆水月\n
[00:08:14]歌词编辑: Mr. Chen\n
[00:24:59]点燃忽明灭的烟\n
[00:28:83]回忆追溯在这漫长黑夜\n
[00:34:47]眼泪被时间冻结\n
[00:37:43]爱情定格在那天\n
[00:40:00]相机里保存着你我的画面\n
[00:46:24]破旧的老照片牵起她的回忆\n
[00:48:95]尘封在房间的角落没人想会起\n
[00:51:68]深夜里拨打着你四年前的手机\n
[00:54:35]这次传来的不是欠费是你温柔的声音\n
[00:57:32]准备好的话语全部都哽噎在嘴边\n
[00:59:85]泪流面的瞬间诠释没有你的时间\n
[01:02:59]窗外的黑夜寒风呼啸阴雨天\n
[01:05:19]我想此刻难眠 好想再见你一面\n
[01:08:21]我伫立在隧道中倾听风的蔓延\n
[01:10:63]蔓延在黑夜中溶于内心的思念\n
[01:13:40]你送我的手表还记录着我们的时间\n
[01:16:08]记录着我们说说笑笑的那个海边\n
[01:18:62]那年夏天那个午后那个银杏树下\n
[01:21:63]我牵着你的手你生气的说要走\n
[01:24:12]最后一声猪头我爱你不要走\n
[01:27:24]可不可以陪我到时间的尽头\n
[01:29:88]还是忘不了你笑脸\n
[01:34:22]每过一天心就越痛一遍\n
[01:39:87]静 止的时间\n
[01:43:10]波 动的眷恋\n
[01:45:79]有一天我们还会再见\n
[01:51:57]岁月流转流年偷换\n
[01:56:93]青春离我们渐行渐远\n
[02:00:31]这个世界没有偶然\n
[02:03:32]给自己一个放任的理由\n
[02:05:16]但别忘了最初的自己\n
[02:07:92]阳光穿透泛白的记忆\n
[02:10:82]微笑对待单纯的自己\n
[02:24:02]眼泪被时间冻结\n
[02:26:48]爱情定格在那天\n
[02:29:09]相机里保存着你我的画面\n
[02:35:30]不知不觉又过了多少年\n
[02:42:44]年少的我们都变了容颜\n
[02:48:27]青丝变白发\n
[02:51:04]皱纹布满的脸颊\n
[02:53:71]如今的你还会说爱我吗\n
[02:59:39]相爱注定痛苦吗\n
[03:04:30]为何分手还是忘不了他\n
[03:09:96]河岸旁的鸳鸯\n
[03:12:80]诗人泪流两行\n
[03:15:50]写在天空的的下一句在哪\n
`)
const props = defineProps({
    isPlay: {
        type: Boolean,
        default: false
    },
    // 当前播放时间
    currentTime: {
        type: Number,
        default: 0
    },
    // 歌曲总时长
    duration: {
        type: Number,
        default: 0
    },
    // 歌词
    // lyric: {
    //     type: String,
    //     default: ''
    // }
})

const lyricRef = ref(null);
// 处理后的歌词数组
const lyricArr = computed(() => {
    const arr = mockLyric.value.split('\n');
    const lyricArr = [];
    arr.forEach((item) => {
        const time = item.substring(item.indexOf('[') + 1, item.indexOf(']'));
        const text = item.substring(item.indexOf(']') + 1);
        const timeArr = time.split(':');
        // 获取时间，并将时间转换为毫秒
        const timeStr = Number(timeArr[0]) * 60 + Number(timeArr[1]);
        // 筛选出值为nan的歌词
        if (isNaN(timeStr)) return;
        lyricArr.push({
            time: timeStr * 1000,
            text
        });
    });
    return lyricArr;
});

// 添加高亮的函数
const addLight = (index) =>{
    const lyric = lyricRef.value
    const list = Array.from(lyric.children)
    // 首先清除所有的高亮
    list.forEach((item)=>{
        if(item){ 
           item.classList.remove("highlight") 
        }        
    })
    // 添加高亮显示
    list[index].classList.add("highlight")
}

const currentLyricIndex = ref(-1);

// 计算当前歌词索引
const calculateCurrentLyricIndex = () => {
    for (let i = 0; i < lyricArr.value.length; i++) {
        if (props.currentTime >= lyricArr.value[i].time && (i === lyricArr.value.length - 1 || props.currentTime < lyricArr.value[i + 1].time)) {
            return i;
        }
    }
    return -1;
};

// 歌词滚动
const scrollLyrics = (index) => {
    if (lyricRef.value) {
        const container = lyricRef.value;
        const lineHeight = 28; // 使用高亮歌词的字体大小作为每行高度估计（这里假设高亮歌词高度决定每行高度）
        const containerHeight = container.offsetHeight;//获取
        const startIndex = Math.max(0, index - Math.floor(containerHeight / lineHeight));
        const endIndex = Math.min(lyricArr.value.length - 1, index + Math.floor(containerHeight / lineHeight));
        const visibleLyricCount = endIndex - startIndex + 1;
        const offset = (index - startIndex) * lineHeight;
        container.scrollTop = offset;
    }
};

// 当组件挂载时，如果有歌词数据，初始化歌词滚动位置
onMounted(() => {
    if (lyricArr.value.length > 0) {
        scrollLyrics(0);
    }
});

// 监听父组件传入的属性变化
watch(() => [props.duration, props.currentTime, props.isPlay], () => {
    if (props.isPlay) {
        const newIndex = calculateCurrentLyricIndex();
        if (newIndex !== currentLyricIndex.value) {
            currentLyricIndex.value = newIndex;
            scrollLyrics(newIndex);
            addLight(newIndex)
        }
        if (props.currentTime === props.duration) {
            // 播放结束，滚动到顶部
            if (lyricRef.value) {
                lyricRef.value.scrollTop = 0;
            }
        }
    }
});


</script>

<template>
    <div class="lyric" ref="lyricRef">
        <span v-for="(item, index) in lyricArr" :key="index" class="lineText"
            >{{ item.text }}</span>
    </div>
</template>

<style lang="scss" scoped>
@keyframes lyricIn {
    0% {
        transform: translate(-100%, 0);
    }

    100% {
        transform: translate(0, 0);
    }
}

.lyric {
    width: 260px;
    height: 600px;
    display: flex;
    // justify-content: center;
    flex-direction: column;
    align-items: center;
    margin: 20px 0;
    transform: rotateY(40deg);
    animation: lyricIn .3s ease-in-out;
    transition: all .3s linear;
    overflow: scroll;

    // 隐藏滚动条
    &::-webkit-scrollbar {
        display: none;
    }

    span {
        // line-height: 20px;
        text-align: center;
        font-size: 18px;
        color: #C7C9D0;
        margin-top: 10px;
    }

    .lineText {
        display: block;
    }

    // 当前播放的歌词
    .highlight {
        color: #fff;
        font-size: 28px;
    }
}
</style>